package service

import (
	"context"
	"errors"
	"gf/app/dao"
	"gf/app/model"
	"gf/library/jwt"
	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"strings"
)

var User = userService{}

type userService struct {}

func (s *userService) SignIn(ctx context.Context, username, password string) (string, error) {
	var user *model.User

	//err := dao.GfUser.Ctx(ctx).Where("username=? ", username).Unscoped().Scan(&user)
	err := dao.GfUser.Ctx(ctx).Where("username=? ", username).Scan(&user)
	if err != nil {
		return "",err
	}

	if user == nil {
		return "", errors.New("账号或密码错误")
	}

	var build strings.Builder
	build.WriteString(password)
	build.WriteString(user.Salt)
	pwd := build.String()

	md5Pwd, _ := gmd5.Encrypt(pwd)

	if md5Pwd != user.Password {
		return "", errors.New("账号或密码错误")
	}

	uid := gconv.String(user.Id)

	exp := g.Cfg().GetString("jwt.exp")
	token,err := jwt.CreateToken(uid, jwt.Secret,gconv.Duration(exp))
	if err != nil{
		return "", errors.New("token 生成失败")
	}

	return token, nil
}

func (s *userService) ResetPassword(ctx context.Context, username, password string) (string, error) {
	var user *model.User

	err := dao.GfUser.Ctx(ctx).Where("username=? ", username).Scan(&user)
	if err != nil {
		return "",err
	}

	if user == nil {
		return "", errors.New("用户信息获取失败")
	}

	var build strings.Builder
	build.WriteString(password)
	build.WriteString(user.Salt)
	pwd := build.String()

	md5Pwd, _ := gmd5.Encrypt(pwd)

	_, err = dao.GfUser.Ctx(ctx).
		Where("id=? ", user.Id).
		Data(g.Map{"password": md5Pwd}).
		Update()
	if err != nil {
		return "", errors.New("重置密码失败")
	}

	exp := g.Cfg().GetString("jwt.exp")
	token,err := jwt.CreateToken(gconv.String( user.Id), jwt.Secret,gconv.Duration(exp))
	if err != nil{
		return "", errors.New("token 生成失败")
	}

	return token, nil
}

